#!/bin/bash
# 修复 protoc 编译问题的脚本

set -e

echo "======================================"
echo "  修复 KWDB SDK Protobuf 编译问题"
echo "======================================"

# 检查是否是 root
if [ "$EUID" -eq 0 ]; then 
   echo "⚠️  请不要使用 sudo 运行此脚本"
   echo "脚本会在需要时提示输入密码"
   exit 1
fi

# 1. 检查当前 protoc 状态
echo ""
echo "1. 检查当前 protoc 状态..."
if command -v protoc &> /dev/null; then
    PROTOC_VERSION=$(protoc --version | awk '{print $2}')
    PROTOC_PATH=$(which protoc)
    echo "   ✅ protoc 已安装"
    echo "   版本: $PROTOC_VERSION"
    echo "   路径: $PROTOC_PATH"
else
    echo "   ❌ protoc 未安装"
fi

# 2. 安装 protoc
echo ""
echo "2. 安装/更新 protobuf 编译器..."

if [ -f /etc/debian_version ]; then
    # Debian/Ubuntu
    echo "   检测到 Debian/Ubuntu 系统"
    sudo apt-get update
    sudo apt-get install -y protobuf-compiler libprotobuf-dev
elif [ -f /etc/redhat-release ]; then
    # RHEL/CentOS
    echo "   检测到 RHEL/CentOS 系统"
    sudo yum install -y protobuf protobuf-devel protobuf-compiler
else
    echo "   ⚠️  未识别的系统，请手动安装 protoc"
    exit 1
fi

# 3. 验证安装
echo ""
echo "3. 验证 protoc 安装..."
if command -v protoc &> /dev/null; then
    protoc --version
    echo "   ✅ protoc 安装成功"
else
    echo "   ❌ protoc 安装失败"
    exit 1
fi

# 4. 清理 Maven 缓存
echo ""
echo "4. 清理 Maven protobuf 插件缓存..."
rm -rf ~/.m2/repository/org/xolstice
rm -rf ~/.m2/repository/com/google/protobuf
echo "   ✅ Maven 缓存已清理"

# 5. 清理项目编译缓存
echo ""
echo "5. 清理项目编译缓存..."
cd /home/kvgroup/chaomei/kwdb_jx/KWDB-sdk/java-sdk
rm -rf target/
echo "   ✅ 项目缓存已清理"

# 6. 尝试重新编译
echo ""
echo "6. 尝试重新编译 Java SDK..."
echo "   这可能需要几分钟时间..."
if mvn clean compile -DskipTests; then
    echo ""
    echo "   ✅ 编译成功！"
else
    echo ""
    echo "   ❌ 编译仍然失败"
    echo ""
    echo "请尝试以下步骤："
    echo "  1. 查看详细错误: mvn clean compile -X"
    echo "  2. 检查网络连接"
    echo "  3. 查看文档: Linux环境编译部署指南.md"
    exit 1
fi

echo ""
echo "======================================"
echo "  问题已修复！"
echo "======================================"
echo ""
echo "现在可以运行："
echo "  cd /home/kvgroup/chaomei/kwdb_jx/KWDB-sdk/java-sdk"
echo "  mvn clean package -DskipTests"
echo ""

